# coding: utf-8
from PySide6.QtCore import Qt
from PySide6.QtWidgets import QWidget, QVBoxLayout, QCompleter, QGridLayout, QSizePolicy
from qfluentwidgets import SingleDirectionScrollArea, BodyLabel, SearchLineEdit, setFont, InfoBar

from common import VoiceThread, signalBus
from components import TTSCard, NoDataCard


class VoicesInterface(SingleDirectionScrollArea):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.view = QWidget()
        self.verticalLayout = QVBoxLayout(self.view)
        self.titleLabel = BodyLabel('TTS 声音', self)
        self.searchLineEdit = SearchLineEdit(self)
        self.gridLayout = QGridLayout()
        self.hintLabel = NoDataCard(self)

        self.voiceThread = VoiceThread(self)

        self.__initWidgets()
        defaultLanguage = 'zh-CN'
        self.searchLineEdit.setText(defaultLanguage)
        self.setLanguage(defaultLanguage)

    def __initWidgets(self):
        self.setObjectName('VoicesInterface')
        self.setWidget(self.view)
        self.setWidgetResizable(True)
        self.view.setAutoFillBackground(False)
        self.enableTransparentBackground()

        setFont(self.titleLabel, 33)
        self.searchLineEdit.setClearButtonEnabled(True)
        self.searchLineEdit.setPlaceholderText('请输入国家地域的语言代码 (ISO Code)')
        self.hintLabel.setVisible(False)

        self.verticalLayout.setAlignment(Qt.AlignmentFlag.AlignTop)
        self.verticalLayout.setContentsMargins(0, 0, 10, 10)
        self.verticalLayout.addSpacing(20)
        self.verticalLayout.addWidget(self.titleLabel)
        self.verticalLayout.addSpacing(20)
        self.verticalLayout.addWidget(self.searchLineEdit)
        self.gridLayout.setAlignment(Qt.AlignmentFlag.AlignTop)
        self.gridLayout.setContentsMargins(0, 0, 0, 0)
        self.gridLayout.setHorizontalSpacing(10)
        self.gridLayout.setVerticalSpacing(10)
        self.gridLayout.setAlignment(Qt.AlignmentFlag.AlignTop)
        self.verticalLayout.addLayout(self.gridLayout)
        self.verticalLayout.addWidget(self.hintLabel, 1, Qt.AlignmentFlag.AlignHCenter)
        self.verticalLayout.addStretch(1)

        self.searchLineEdit.searchSignal.connect(self.onSearch)
        self.searchLineEdit.searchButton.setShortcut(Qt.Key.Key_Return)
        self.voiceThread.languageChanged.connect(self.onLanguageChanged)
        self.voiceThread.voiceChanged.connect(self.onVoiceChanged)
        self.voiceThread.finished.connect(
            lambda: InfoBar.info(
                '搜索结果',
                f'搜索到 {self.gridLayout.count()} 个结果',
                parent=self
            )
        )

    def onLanguageChanged(self, language: list):
        completer = QCompleter(language, self.searchLineEdit)
        completer.setCaseSensitivity(Qt.CaseSensitivity.CaseInsensitive)
        completer.setMaxVisibleItems(10)
        self.searchLineEdit.setCompleter(completer)

    def onVoiceChanged(self, voices: list):
        if not voices:
            self.hintLabel.setVisible(True)
            return
        self.hintLabel.setVisible(False)
        for index, voice in enumerate(voices):
            item = TTSCard(self)
            item.setUserData(voice)
            item.setCheckable(False)
            item.clicked.connect(
                lambda x, v=voice:
                signalBus.switchToSample.emit(
                    'conversionInterface',
                    {
                        'language': self.searchLineEdit.text(),
                        'shortName': v['ShortName']
                    }
                )
            )
            item.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
            self.gridLayout.addWidget(item, index // 3, index % 3, 1, 1, Qt.AlignmentFlag.AlignTop)

    def setLanguage(self, language: str):
        self.voiceThread.setKey(language)

    def onSearch(self, text: str):
        self.clear()
        self.setLanguage(text)

    def clear(self):
        while self.gridLayout.count():
            item = self.gridLayout.takeAt(0)
            if item.widget():
                self.gridLayout.removeWidget(item.widget())
                item.widget().deleteLater()
            self.gridLayout.removeItem(item)
            del item
